<template>
  <div class="tenant-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>租客管理</span>
          <el-button type="primary" @click="handleAddTenant" class="add-button">
            <el-icon-plus /> 添加租客
          </el-button>
        </div>
      </template>

      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入租客姓名、房间号或联系方式"
          prefix-icon="Search"
          class="search-input"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>

      <el-table v-loading="loading" :data="tenantList" style="width: 100%">
          <el-table-column prop="id" label="租客ID" width="180" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="phone" label="联系方式" width="150" />
          <el-table-column prop="roomNumber" label="房间号" width="100" />
          <el-table-column prop="idCard" label="身份证号" width="180" />
          <el-table-column prop="homeAddress" label="家庭地址"/>
          <el-table-column prop="leaseStartDate" label="租期开始" width="150" />
          <el-table-column prop="leaseEndDate" label="租期结束" width="150" />
          <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === '正常' ? 'success' : scope.row.status === '预警' ? 'warning' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click="handleEditTenant(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteTenant(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑租客对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" draggable width="760px">
      <el-form :model="formData" ref="formRef" :rules="rules" label-width="150px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="家庭地址" prop="homeAddress">
          <el-input v-model="formData.homeAddress" placeholder="请输入身份证上的家庭地址" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="formData.roomNumber" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="租期开始" prop="leaseStartDate">
          <el-date-picker v-model="formData.leaseStartDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="租期结束" prop="leaseEndDate">
          <el-date-picker v-model="formData.leaseEndDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContactName">
          <el-input v-model="formData.emergencyContactName" placeholder="请输入紧急联系人" />
        </el-form-item>
        <el-form-item label="紧急联系人电话" prop="emergencyContactPhone">
          <el-input v-model="formData.emergencyContactPhone" placeholder="请输入紧急联系人电话" />
        </el-form-item>
        <el-form-item label="公司信息" prop="companyInfo">
          <el-input v-model="formData.companyInfo" placeholder="请输入公司名称或上班地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="NORMAL" />
            <el-option label="预警" value="WARNING" />
            <el-option label="违约" value="BREACH" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import userService from '../../services/userService.ts'

// 搜索相关
const searchQuery = ref('')

// 表格数据相关
const tenantList = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加租客')
const formData = reactive({
  id: "",
  name: "韦海宇",
  phone: "15798480907",
  homeAddress: "广西柳州市",
  idCard: "450221199210264918",
  emergencyContactName: "韦哒哒",
  emergencyContactPhone: "17786435945",
  roomNumber: "405-3",
  companyInfo: "深圳市科技有限公司",
  leaseStartDate: "2025-08-04T16:00:00.000Z",
  leaseEndDate: "2025-08-26T16:00:00.000Z",
  status: "NORMAL",
})
const formRef = ref<any>(null)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  emergencyContact: [{ required: true, message: '请输入紧急联系人', trigger: 'blur' }],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  roomNumber: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  companyInfo: [{ required: false, message: '请输入公司名称或上班地址', trigger: 'blur' }],
  leaseStartDate: [{ required: true, message: '请选择租期开始日期', trigger: 'change' }],
  leaseEndDate: [{ required: true, message: '请选择租期结束日期', trigger: 'change' }]
}

// 生命周期钩子
onMounted(() => {
  fetchTenantList()
})

// 获取租客列表
const fetchTenantList = () => {
  loading.value = true
  userService.getUserList(currentPage.value, pageSize.value, searchQuery.value).then((res:any) => {
    console.log(res);
    if(res.code === 200){
      tenantList.value = res.data
      total.value = res.totalPage
      loading.value = false
    }
  }).catch((error:any) => {
    console.error(error);
    ElMessage.error('获取租客列表失败')
  }).finally(()=>{
    loading.value = false
  })
}

// 搜索事件
const handleSearch = () => {
  currentPage.value = 1
  fetchTenantList()
}

// 分页事件
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchTenantList()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  fetchTenantList()
}

// 添加租客
const handleAddTenant = () => {
  dialogTitle.value = '添加租客'
  // 重置表单
  // formData.id = ''
  // formData.name = ''
  // formData.phone = ''
  // formData.emergencyContactName = ''
  // formData.emergencyContactPhone = ''
  // formData.idCard = ''
  // formData.roomNumber = ''
  // formData.companyInfo = ''
  // formData.leaseStartDate = ''
  // formData.leaseEndDate = ''
  // formData.status = '正常'
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = true
}

// 编辑租客
const handleEditTenant = (row: any) => {
  dialogTitle.value = '编辑租客'
  // 填充表单数据
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row: any) => {
  // 这里可以跳转到详情页或显示详情对话框
  ElMessage({
    message: `查看租客${row.name}的详情`,
    type: 'info'
  })
}

// 删除租客
const handleDeleteTenant = (id: number) => {
  ElMessage({
    message: `删除租客ID: ${id}`,
    type: 'success'
  })
  // 重新获取列表
  fetchTenantList()
}

// 提交表单
const handleSubmit = () => {
  loading.value = true
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟提交
     userService.createUser(formData).then((res:any) => {
       if(res.code === 200){
        ElMessage({
          message: formData.id ? '编辑成功' : '添加成功',
          type: 'success'
        })
        dialogVisible.value = false
        fetchTenantList()
       }
     }).catch((error:any) => {
      console.error(error);
      ElMessage.error('添加租客失败')
     }).finally(() => {
       loading.value = false
     })
    }
  })
}
</script>

<style scoped>
.tenant-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-button {
  margin-top: 5px;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 确保表格正确显示 */
:deep(.el-table__inner-wrapper) {
  table-layout: auto !important;
}

:deep(.el-table th) {
  text-align: center !important;
}

:deep(.el-table td) {
  text-align: center !important;
}
</style>